
var tabbarJs = require("../tabbar/tabbar.js");
var init = tabbarJs.init;
var onTabbarItemTap = tabbarJs.onTabbarItemTap;
var modelImgUrl="../../images/";
var requestMode = require('../../js/requestsMode.js');
var session = require('../../js/session.js');
var constants = require('../../js/constants.js');
////吐司工具
var Tools = require("../../js/Tools.js");
function getWindowSize(){
    var windowWidth=0;
    var windowHeight=0;
    wx.getSystemInfo({
        success: function (res) {
            windowWidth = res.windowWidth;
            windowHeight = res.windowHeight;
        }
    });
    return {
        "windowWidth" : windowWidth,
        "windowHeight" : windowHeight
    }
}
var windowWidth= getWindowSize().windowWidth;
var allShopping=[];
var allShoppingLength = allShopping.length;

//计算总选择数量
var hasChoseShopping = 0;
function getHasChoseShoppingNumber(data){
    for(var i in data){
        if(data[i]['is_check'] == true){
            hasChoseShopping++;
        }
    }
}
getHasChoseShoppingNumber(allShopping);

//计算总价格
var allPrice = 0;
function getAllPrice(data){
    for(var ii in data){
        if(data[ii]['is_check'] == true){
            allPrice = allPrice+(data[ii]['space_price']*data[ii]['number']);
        }
    }
}
getAllPrice(allShopping);

//全选操作
function choseALLshopping(data){
    for(let i in data){
        data[i]['is_check'] = true;
    }
}

//不全选操作
function notChoseALLshopping(data){
    for(let i in data){
        data[i]['is_check'] = false;
    }
}

//总价格格式化
function setPrice(Price){
    Price = String(Price);
    let afterNumber =Price .lastIndexOf(".");
    if(afterNumber != -1){
        Price = Price.substring( 0,(Price.indexOf(".")+3) );
    }
    let returnPrice = parseFloat(Price).toFixed(2);
    return returnPrice;
}
let PageData = {
    data:{
        ///总页数
        page_total : 0,
        page : 1,
        allShoppingLength :allShoppingLength,
        jhDataForTabbar : Tools.tabBarItems(2,0),
        hasChoseShopping :hasChoseShopping,  //已选择数量
        allShopping:allShopping,  //所有商品
        allPrice:allPrice,          //总价格
        choseStyleImg : modelImgUrl+'carChoseStyle.png',
        modelWidth: windowWidth*2-60-40,
        choseAll:false,
        addImg:modelImgUrl+'add.png',
        reduceImg:modelImgUrl+'reduce.png',
        notShopping:modelImgUrl+'notOrder.png',
        willDelId:null,
        startX: 0, //开始坐标
        startY: 0,
        delAnimation:'transform:translateX('+-(windowWidth+100)+'px);transition:all 0.3s;',
        listLength : 0
    },
    ///页面进入回调
    onShow : function() {
        Tools.requestBuyCarCount(false,this,2);
        this.setData({
                page : 1,
                allShopping : []
            }
        );
        this.requestCarList();
    },
    ///下拉刷新方法
    onPullDownRefresh: function () {
        this.setData({
            page: 1,
            allShopping:[]
        });this.requestCarList();
    },
    ///触发上拉加载更多
    onReachBottom: function (){
        if (this.data.page >= this.data.page_total) {
            return;
        }
        let that = this;
        this.setData({
            page: that.data.page + 1
        });
        this.requestCarList();
    },
    /*请求购物车列表*/
    requestCarList : function() {
        let that = this;
        let newAllshopping = that.data.allShopping;
        if(this.data.page == 0) {
            newAllshopping = [];
        }
        Tools.showLoaddingDefault();
        requestMode.sendRequest('shop-cart/list', 'POST', { type: 1, page: this.data.page, size: constants.size }, {sKey:session.get("sKey")}).then(function (requestSucessRes) {
            let code = requestSucessRes.data.code;
            if (code == 200) {
                Tools.hideLoaddingToast();
                that.setData({
                    page_total : requestSucessRes.data.data.page_total
                });
                let getData = requestSucessRes.data.data.list;
                for (var tempIndex = 0;tempIndex < getData.length;tempIndex++) {
                    let carModel = getData[tempIndex];
                    carModel['isTouchMove'] = false;
                    carModel['is_check'] = false;
                    newAllshopping.push(carModel);
                }
                that.setData({
                    allShopping : newAllshopping,
                    listLength : newAllshopping.length
                });
                //请求成功
                if (that.data.choseAll == true) {//如果当前是全选状态，先去掉全选然后全部全选
                    newAllshopping.forEach(function(value){
                        value['is_check'] = true;
                    });
                    that.setData({ choseAll:false });
                    that.choseAll();
                }
            } else {
                Tools.showErrorToast(requestSucessRes.data.message);
            }
        }, function () {
            Tools.showWrongNetWorkToast();
        })
    },
    onTabbarItemTap:onTabbarItemTap,
    choseAll:function(){
        let ifchoseall = this.data.choseAll;
        let afterChoseAll_shopping = this.data.allShopping;
        if(ifchoseall == true){
            ifchoseall = false;
            notChoseALLshopping(afterChoseAll_shopping);
        }else{
            ifchoseall = true;
            choseALLshopping(afterChoseAll_shopping);
        }
        hasChoseShopping = 0;
        allPrice =0;
        getAllPrice(afterChoseAll_shopping);
        getHasChoseShoppingNumber(afterChoseAll_shopping);
        this.setData({
            choseAll : ifchoseall,
            allShopping : afterChoseAll_shopping,
            hasChoseShopping : hasChoseShopping,
            allPrice:setPrice(allPrice)
        })
    },
    seeDetailed:function(e){
        let the_id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url:'../type/detailed/detailed?id='+the_id
        })
    },
    intIfChose:function(e){
        var the_id = e.currentTarget.dataset.id;
        var the_chose = e.currentTarget.dataset.chose;
        var IntChose = true;
        if(the_chose == true){
            IntChose = false;
        }else{
            IntChose = true;
        }
        const This =this;
        let NEW_allShopping = This.data.allShopping;
        for(let current=0;current< NEW_allShopping.length;current++){
            if( NEW_allShopping[current]['shop_cart_id'] == the_id){
                NEW_allShopping[current]['is_check'] = IntChose;
                break;
            }
        }
        hasChoseShopping = 0;
        getHasChoseShoppingNumber(NEW_allShopping);
        if(hasChoseShopping >= NEW_allShopping.length) {        ///已经选中了所有的购物车列表  相当于点击了全选
            This.setData({
                choseAll:true
            });
        }
        allPrice = 0;
        getAllPrice(NEW_allShopping);
        This.setData({
            allShopping : NEW_allShopping,
            hasChoseShopping :hasChoseShopping,
            allPrice:setPrice(allPrice)
        });
    },
    numberChange:function(e){
        let This = this;
        let id = e.currentTarget.dataset.id;
        let number =e.detail.value;
        if(number == 0 || number == ""){
            number=1;
        }
        let NEW_allShopping = This.data.allShopping;
        for(let current=0;current< NEW_allShopping.length;current++){
            if( NEW_allShopping[current]['shop_cart_id'] == id){
                NEW_allShopping[current]['number'] = number;
            }
        }
        allPrice = 0;
        getAllPrice(NEW_allShopping);
        This.setData({
            allShopping : NEW_allShopping,
            allPrice:setPrice(allPrice)
        });
        this.updateNumRequest(id,number);
    },
    ///数量增加方法
    addThis:function(e){
        let id = e.currentTarget.dataset.id;
        let number =e.currentTarget.dataset.number;
        if(number <= 0 || number == ""){
            number=1;
            this.updateNumRequest(id,number);
        }else{
            if(number >= 1){
                number++;
                this.updateNumRequest(id,number);
            }else{
                number=1;
            }
        }
    },
    ///数量减少方法
    reduceThis:function(e){
        let id = e.currentTarget.dataset.id;
        let number =e.currentTarget.dataset.number;
        if(number <= 0 || number == ""){
            number = 1;
            this.updateNumRequest(id,number);
        }else{
            if(number > 1){
                ////数量变化请求接口
                number--;
                this.updateNumRequest(id,number);
            }else{
                number=1;
            }
        }

    },



    ///更新购物车数量请求
    updateNumRequest : function (currentId,currentNum) {
        ///出现加载框
        let that = this;
        Tools.showLoaddingDefault();
        ///网络请求开始
        requestMode.sendRequest("shop-cart/modify","POST",{"shop_cart_id":currentId,"number":currentNum},{"sKey":session.get("sKey")}).then(
            function (requestSucessRes)
            {
                ///网络请求成功
                let resultCode = requestSucessRes.data.code;
                if (resultCode == 200)
                {
                    Tools.hideLoaddingToast();
                    that.reloadAllPriceandListWhenAddReduce(currentId,currentNum);
                }else
                {
                    Tools.showErrorToast(requestSucessRes.data.message);
                }
            },function (requestFailRes)
            {
                Tools.showWrongNetWorkToast();
            }
        );
    },

    ///当点击增加数量或者减少数量的时候刷新全部价格和列表
    reloadAllPriceandListWhenAddReduce : function (currentId,currentNumber) {
        let NEW_allShopping = this.data.allShopping;
        for(let current=0;current< NEW_allShopping.length;current++){
            if( NEW_allShopping[current]['shop_cart_id'] == currentId){
                NEW_allShopping[current]['number'] = currentNumber;
            }
        }
        allPrice = 0;
        getAllPrice(NEW_allShopping);
        this.setData({
            allShopping : NEW_allShopping,
            allPrice:setPrice(allPrice)
        });
    },
    //提交订单事件
    submitOrder:function(e){
        var shopArray = [];
        let data = this.data.allShopping;
        let shop_cart_ids=[];
        for(let tempIndex in data){
            if(data[tempIndex]['is_check'] == true){
                shop_cart_ids.push(data[tempIndex]['shop_cart_id']);
                shopArray.push(data[tempIndex]);
            }
        }
        wx.navigateTo({
            url:'../mines/confirmationOrder/confirmationOrder?shopArray=' + JSON.stringify(shopArray)+"&shop_cart_ids="+shop_cart_ids.toString()
        })
    },
    ////点击开始手势
    touchstart: function (e) {
        this.data.allShopping.forEach(function (v, i) {
            if (v.isTouchMove)
                v.isTouchMove = false;
        });
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            allShopping: this.data.allShopping
        })
    },

    angle: function (start, end) {
        let _X = end.X - start.X,
            _Y = end.Y - start.Y;
        //返回角度 /Math.atan()返回数字的反正切值
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    ///移动手势
    touchmove: function (e) {
        let that = this,
            index = e.currentTarget.dataset.index,//当前索引
            startX = that.data.startX,//开始X坐标
            startY = that.data.startY,//开始Y坐标
            touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
            touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
            angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
        that.data.allShopping.forEach(function (v, i) {
            v.isTouchMove = false;
            //滑动超过30度角 return
            if (Math.abs(angle) > 30) return;
            if (i == index) {
                if (touchMoveX > startX){  //右滑
                    v.isTouchMove = false;
                }
                else {
                    v.isTouchMove = true
                }
            }
        });
        that.setData({
            allShopping: that.data.allShopping
        })
    },
    /*删除购物车网络请求成功之后的动画和操作*/
    deleteCarItemWhenSucess : function (deleteId,indexOfDel) {
        ///重新获取购物车数量并且刷新界面
        Tools.requestBuyCarCount(true,this,2);
        ///执行删除之后的动画
        let that = this;
        let allShopping = this.data.allShopping;
        let maxCurrent = allShopping.length;
        let delNextBrotherId='';
        for(let i =0;i<maxCurrent;i++){
            if(allShopping[i]['shop_cart_id'] == deleteId){
                if( i == maxCurrent -1){
                    delNextBrotherId = '';
                }else{
                    delNextBrotherId = allShopping[i+1]['shop_cart_id'];
                }
            }
        }
        this.setData({
            willDelId:deleteId,
            delNextBrotherId:delNextBrotherId
        });
        setTimeout(function(){
            that.setData({
                marginAnimation: 'margin-top:-252rpx;transition:margin-top 0.2s linear;'
            })
        },500);
        allPrice = 0;
        setTimeout(function(){
            let newData = that.data.allShopping;
            newData.splice(indexOfDel, 1);
            let  listLength = newData.length;
            getAllPrice(newData);
            that.setData({
                marginAnimation: '',
                allShopping: newData,
                allPrice:setPrice(allPrice),
                listLength : listLength
            });
        },720);
    },
    /*删除购物车的某一项网络请求*/
    del: function (e) {
        let that = this;
        let indexOfDel = e.currentTarget.dataset.index;
        let idOfDel = e.currentTarget.dataset.id;
        Tools.showLoaddingDefault();
        requestMode.sendRequest("shop-cart/remove","POST",{shop_cart_id:idOfDel},{sKey:session.get("sKey")}).then(
            function(requestSucessRes) {
                Tools.hideLoaddingToast();
                let code = requestSucessRes.data.code;
                if (code == 200) {
                    that.deleteCarItemWhenSucess(idOfDel,indexOfDel);
                }else {
                    Tools.showErrorToast(requestSucessRes.data.message);
                }
            },function(requestFailRes) {
                Tools.showWrongNetWorkToast();
            }
        );
    }
};
init(PageData);